<template>
    <view class="swiper-tabs">
        <scroll-view 
        ref="tabbar1" 
        class="tab-bar" 
        :scroll="false" 
        :scroll-x="true" 
        :enable-flex="true"
        :throttle="false"
        :scroll-left="scrollToLeft"
        :show-scrollbar="false" 
        scroll-with-animation>
            <view style="flex-direction: column;">
                <view style="flex-direction: row;">
                    <view class="uni-tab-item" v-for="(tab,index) in tabList" :key="tab.id" :id="tab.id" :ref="'tabitem'+index"
                        :data-id="index" :data-current="index" @click="ontabtap">
                        <text class="uni-tab-item-title" :class="tabIndex==index ? 'uni-tab-item-title-active' : ''">{{tab.name}}</text>
                    </view>
                </view>
                <view class="scroll-view-indicator">
                    <view ref="underline" class="scroll-view-underline" :class="isTap ? 'scroll-view-animation':''"
                        :style="{left: indicatorLineLeft + 'px', width: indicatorLineWidth + 'px'}"></view>
                </view>
            </view>
        </scroll-view>
        <view class="tab-bar-line"></view>
        <swiper 
        class="swiper-view" 
        ref="swiper1" 
        :current="tabIndex" 
        :duration="300" 
        @change="onswiperchange"
        @transition="onswiperscroll" 
        @animationfinish="animationfinish" 
        @onAnimationEnd="animationfinish">
            <swiper-item class="swiper-item" v-for="(page, index) in tabLists" :key="index">
                <!-- <slot :refresher="refresher" :page="page" :itemIndex="index" :data="{page,itemIndex:index}"/> -->
                <swiperPage 
                :params="params"
                :refresher="refresher" 
                :item="page" 
                :itemIndex="index" 
                :refresher-color="refresherColor"
                :top-button="topButton"
                @setPageData="setPageData"
                ref="page" 
                class="swiper-page">
                    <template #header>
		                <slot :page="page" :itemIndex="index" name="header"/>
                    </template>
		            <slot name="top"/>
					<slot :page="page" :itemIndex="index" :nowSubList="nowSubList" />
                    <!-- <template v-slot:item="{ data, isLoading, finish }">
					    <slot :itemIndex="index" :data="data" :page="page" :isLoading="isLoading" :finish="finish"/>
				        <div>{{data[0]}} {{isLoading}}</div>
                    </template> -->
                </swiperPage>
            </swiper-item>
        </swiper>
    </view>
</template>

<script>
    import { testApi } from '@/api'
    import { objectMerge } from '@/utils'

    // 缓存每页最多
    const MAX_CACHE_DATA = 20;

    // 缓存页签数量
    const MAX_CACHE_PAGE = 3;
    const TAB_PRELOAD_OFFSET = 1;

    import swiperPage from './swiper-page.vue';

    export default {
	    name: 'mo-swiper-list',
        components: {
            swiperPage,
        },
        props: {
            nowSubList: {
                type: Object,
                default: ()=>{}
            },
            params: {
                type: Object,
                default: ()=>{}
            },
            current: {
                type: [Number],
                default: 0
            },
            tabList: {
                type: Array,
                default: ()=>[]
            },
			refresherColor: {
				type: String,
				default: 'transparent'
			},
			topButton: {
				type: Boolean,
				default: true
			},
        },
        data() {
            return {
                tabLists: [],
                tabIndex: 0,
                scrollToLeft: 0,
                cacheTab: [],
                indicatorLineLeft: 0,
                indicatorLineWidth: 0,
                isTap: false,
                refresher: true,
            }
        },
        watch:{
            tabList: {
                handler(newVal,oldVal){
                    this.tabLists=newVal;
                    this.$nextTick(function(){
                        this.init(this.current);
                    })
                },
                immediate: true
            }
        },
        created(){
            this.tabIndex = this.current||0;
        },
        mounted() {
            // this.init(this.current);
        },
        methods: {
            setPageData(data){
                const list = objectMerge([], this.tabLists)
                this.tabLists = list.reduce((t,c,i)=>{
                    if(i == this.tabIndex){
                        c.data = data
                    }
                    return t.concat(c)
                },[])
            },
            init(index){
                this._lastTabIndex = index
                // #ifdef MP-WEIXIN
                this._lastTabIndex = index-1?index:0;
                // #endif
                this.swiperWidth = 0;
                this.tabListSize = {};
                this._touchTabIndex = index||0;

                // #ifndef MP-ALIPAY
                this.pageList = this.$refs.page;
                // #endif
                // console.log(96,this.pageList)

                if(!this.pageList) return
                this.switchTab(this.tabIndex);

                this.getTabbarItemsSize();
            },
            scroll(e){
                this.scrollToLeft = e.detail.scrollLeft
            },
            ontabtap(e) {
                const index = e.target.dataset.current || e.currentTarget.dataset.current;

                // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
                this.isTap = true;
                const currentSize = this.tabListSize[index];
                this.updateIndicator(currentSize.left, currentSize.width);
                this._touchTabIndex = index;
                // #endif

                this.switchTab(index);
            },
            onswiperchange(e) {
                // 注意：百度小程序会触发2次

                // #ifndef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
                let index = e.target.current || e.detail.current;
                this.switchTab(index);
                // #endif
            },
            onswiperscroll(e) {
                if (this.isTap) return
                this.refresher = false

                const offsetX = e.detail.dx;
                let preloadIndex = this._lastTabIndex;
                if (offsetX > TAB_PRELOAD_OFFSET) {
                    preloadIndex++;
                } else if (offsetX < -TAB_PRELOAD_OFFSET) {
                    preloadIndex--;
                }
                if (preloadIndex === this._lastTabIndex || preloadIndex < 0 || preloadIndex > this.pageList.length - 1) {
                    return;
                }
                // if (this.pageList[preloadIndex].data.length === 0) {
                //     this.loadTabData(preloadIndex);
                // }

                /// 计算 tabbar 底线
                // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
                const percentage = Math.abs(this.swiperWidth / offsetX);
                const currentSize = this.tabListSize[this._lastTabIndex];
                const preloadSize = this.tabListSize[preloadIndex];
                const lineL = currentSize.left + (preloadSize.left - currentSize.left) / percentage;
                const lineW = currentSize.width + (preloadSize.width - currentSize.width) / percentage;
                this.updateIndicator(lineL, lineW);
                // #endif
            },
            animationfinish(e) {
                this.refresher = true
                // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
                let index = e.detail.current;
                if (this._touchTabIndex === index) {
                    this.isTap = false;
                }
                this._lastTabIndex = index;
                this.switchTab(index);
                this.updateIndicator(this.tabListSize[index].left, this.tabListSize[index].width);
                // #endif
            },
            getTabbarItemsSize() {
                // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
                uni.createSelectorQuery().in(this).select('.swiper-view').fields({
                    dataset: true,
                    size: true,
                }, (res) => {
                    this.swiperWidth = res.width;
                }).exec();

                uni.createSelectorQuery().in(this).selectAll('.uni-tab-item').boundingClientRect((rects) => {
                    rects.forEach((rect) => {
                        this.tabListSize[rect.dataset.id] = rect;
                    })
                }).exec();

                let t = setTimeout(() => {
                    if(!this.tabListSize[this.tabIndex]){
                        clearTimeout(t)
                        this.getTabbarItemsSize()
                    }else{
                        clearTimeout(t)
                        this.updateIndicator(this.tabListSize[this.tabIndex].left, this.tabListSize[this.tabIndex].width);
                    }
                }, 50)
                // #endif
            },
            updateIndicator(left, width) {
                const res = this.tabListSize[this.tabIndex]
                // const offset = res.right > this.swiperWidth/2 ? left - this.swiperWidth/2 + res.width/2 : 0
                const offset = left + res.width/2 - this.swiperWidth/2
                this.scrollToLeft = offset > 0 ? offset : 0
                this.indicatorLineLeft = left + width/4;
                this.indicatorLineWidth = width/2;
            },
            switchTab(index) {
                if (this.pageList[index].data.length === 0) {
                    this.loadTabData(index);
                }
                if (this.tabIndex === index) return;

                // 缓存 tabId
                if (this.pageList[this.tabIndex].data.length > MAX_CACHE_DATA) {
                    let isExist = this.cacheTab.indexOf(this.tabIndex);
                    if (isExist < 0) {
                        this.cacheTab.push(this.tabIndex);
                    }
                }

                this.tabIndex = index;
                this.$emit('onChange',{
                    _index: this.tabIndex,
                    ...this.tabList[this.tabIndex]
                })

                // 释放 tabId
                if (this.cacheTab.length > MAX_CACHE_PAGE) {
                    const cacheIndex = this.cacheTab[0];
                    if(cacheIndex == this.tabIndex) return
                    this.clearTabData(cacheIndex);
                    this.cacheTab.splice(0, 1);
                }

            },
            
            loadTabData(index) {
                if(!this.tabList.length||!this.tabList[index].action) return;
                this.pageList[index].loadData();
            },
            clearTabData(index) {
                // this.tabLists[index].data = []
                this.pageList[index].clear();
            }
        }
    }
</script>

<style lang="scss" scoped>
    $nav-color: #007AFF;
    $nav-pink-color: #000;
    $line-height: 8rpx;
    .swiper-tabs {
        display: flex;
        flex: 1;
        flex-direction: column;
        overflow: hidden;
	    height: 100%;
    }

    .tab-bar {
        // width: 750rpx;
        // height: 84rpx;
        flex-direction: row;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
        box-shadow: 0 5rpx 10rpx rgba($color: #000000, $alpha: .05);
    }

    /* #ifndef APP-NVUE */
    .tab-bar ::-webkit-scrollbar {
        display: none;
        width: 0 !important;
        height: 0 !important;
        -webkit-appearance: none;
        background: transparent;
    }
    /* #endif */

    .scroll-view-indicator {
        position: relative;
        height: $line-height;
        background-color: transparent;
    }

    .scroll-view-underline {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 50rpx;
        height: $line-height;
        background-color: $nav-pink-color;
        border-radius: $line-height $line-height;
    }

    .scroll-view-animation {
        transition-duration: 0.2s;
        transition-property: left;
    }

    .tab-bar-line {
        height: 1rpx;
        background-color: #f5f5f5;
    }

    swiper,.swiper-view {
        flex: 1;
        height: 100%;
        width: 100%;
    }

    .uni-tab-item {
        /* #ifndef APP-PLUS */
        display: inline-block;
        /* #endif */
        flex-wrap: nowrap;
        padding-left: 25rpx;
        padding-right: 25rpx;
        padding-top: 26rpx;
        padding-bottom: 14rpx;
    }

    .uni-tab-item-title {
        color: #555;
        font-size: 32rpx;
        // height: 80rpx;
        // line-height: 80rpx;
        flex-wrap: nowrap;
        transition: color 0.1s;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
    }

    .uni-tab-item-title-active {
        color: $nav-pink-color;
    }

    .swiper-item {
        flex: 1;
        flex-direction: column;
    }

</style>
